package br.com.bean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EngineBean<T> {
	private static final List<String> arrImageSufixes = new ArrayList<String>();
	
	static {
		arrImageSufixes.add(".png");
		arrImageSufixes.add(".gif");
		arrImageSufixes.add(".jpg");
		arrImageSufixes.add(".jpeg");
		arrImageSufixes.add(".bmp");
	}
	
	private List<T> keys;
	private HashMap<T, List<T>> values;
	
	public EngineBean() {
		keys = new ArrayList<T>();
		values = new HashMap<T, List<T>>();
	}
	
	public void append(EngineBean<T> engineBean) {
		if(engineBean == null) return;
				
		for(T key : engineBean.getKeys()) {
			for(T value : engineBean.getValues(key)) {
				this.put(key, value);
			}
		}
	}
	
	public void put(T key, T value) {
		if(keys.contains(key)) {
			values.get(key).add(value);
		} else {
			keys.add(key);
			values.put(key, new ArrayList<T>());
			values.get(key).add(value);
		}
	}
	
	public void remove(T key, T value) {
		if(keys.contains(key) && values.get(key).contains(value)) {
			values.get(key).remove(value);
		}
	}
	
	public void remove(T key) {
		if(keys.contains(key)) {
			keys.remove(key);
			values.remove(key);
		}
	}
	
	public List<T> getKeys () {
		return keys;
	}
	
	public List<T> getValues(T key) {
		return (values.containsKey(key) ? values.get(key) : new ArrayList<T>());
	}
	
	public void clear() {
		keys.clear();
		values.clear();
	}
	
	public int size() {
		return (keys.size() > 0 && values.containsKey(keys.get(0)) ? values.get(keys.get(0)).size() : 0);
	}
	
	public String toString() {
		String retorno = "";
		
		if(keys != null && values != null && !keys.isEmpty()) {
			retorno = "<table border=\"1\">";
			
			retorno += "<tr>";
			for(T key : keys) {
				retorno += "<th>" + key + "</th>";
			}
			retorno += "</tr>";
			
			int rows = values.get(keys.get(0)).size();
			for(int i = 0; i < rows; i++) {
				retorno += "<tr>";
				for(T key : keys) {
					T value = values.get(key).get(i);

					if(isImageURL(value.toString())) {
						retorno += "<td><img src=\"" + value + "\" /></td>";
					} else {
						retorno += "<td>" + value + "</td>";
					}
				}
				retorno += "</tr>";
			}
			
			retorno += "</table>";
		}
		
		return retorno;
	}
	
	private final boolean isImageURL(String uri) {
		for(String sufix : arrImageSufixes) {
			if (uri.endsWith(sufix)) return true; 
		}
		
		return false;
	}
}
